# import os
# import numpy as np
# import pandas as pd
# from read_CloudSat import reader
#
# # 文件路径
# filepath = '/mnt/raid1/liudd/2019365224713_72859_CS_2B-GEOPROF_GRANULE_P1_R05_E09_F00.hdf'
# filepath_lida = '/mnt/raid1/liudd/2019365224713_72859_CS_2B-GEOPROF-LIDAR_GRANULE_P2_R05_E09_F00.hdf'
#
# # 读取数据
# f = reader(filepath)
# d = reader(filepath_lida)
# lon_c, lat_c, elv = f.read_geo()
# height = f.read_sds('Height')
# height = height * 0.001
# cloud_mask = f.read_sds('CPR_Cloud_mask')
# cloud_radar = f.read_sds('Radar_Reflectivity')
# cloud_faction = d.read_sds('CloudFraction')
# time = f.read_time(datetime=True)
# cloudsat_start_time, cloudsat_end_time = time[[0, -1]]
#
#
# cloudsat_cth = []
# cloudsat_cbh = []
# cloud_types = []
#
# # for i, row_data in enumerate(cloud_mask):
# #     # 使用按位操作，确保 cloud_mask >= 20 且 cloud_radar >= -30
# #     valid_mask = (cloud_mask[i, :] >= 20) & (cloud_radar[i, :] >= -30)
# #
# #     if np.any(valid_mask):  # 如果有满足条件的值
# #         col_idx = np.argmax(valid_mask)  # 找到第一个满足条件的位置
# #         last_idx = np.where(valid_mask)[0][-1]  # 找到最后一个满足条件的位置
# #
# #         # 获取云顶高度
# #         cth_value = height[i, col_idx] if col_idx < height.shape[1] else np.nan
# #         cloudsat_cth.append(cth_value)
# #
# #         # 获取云底高度
# #         cbh_value = height[i, last_idx] if last_idx < height.shape[1] else np.nan
# #         cloudsat_cbh.append(cbh_value)
# #
# #         # 判断云类型
# #         if col_idx < last_idx:
# #             between_values = row_data[col_idx + 1:last_idx]  # 从云顶到云底的区域
# #             cloud_type = 1 if np.any(between_values < 20) else 0  # 判断云类型
# #         else:
# #             cloud_type = 0  # 如果云顶和云底相同或无有效数据
# #         cloud_types.append(cloud_type)
# #     else:
# #         cloudsat_cth.append(np.nan)
# #         cloudsat_cbh.append(np.nan)
# #         cloud_types.append(np.nan)
# #
# # cloudsat_cth = np.array(cloudsat_cth)
# # cloudsat_cbh = np.array(cloudsat_cbh)
# # cloud_types = np.array(cloud_types)
#
# for i, row_data in enumerate(cloud_mask):
#     # 使用按位操作，确保 cloud_mask >= 20 且 cloud_radar >= -30
#     valid_mask = (cloud_mask[i, :] >= 20) & (cloud_radar[i, :] >= -30)
#
#     if np.any(valid_mask):  # 如果有满足条件的值
#         col_idx = np.argmax(valid_mask)  # 找到第一个满足条件的位置
#         last_idx = np.where(valid_mask)[0][-1]  # 找到最后一个满足条件的位置
#
#         # 获取云顶高度
#         cth_value = height[i, col_idx] if col_idx < height.shape[1] else np.nan
#         cloudsat_cth.append(cth_value)
#
#         # 获取云底高度
#         cbh_value = height[i, last_idx] if last_idx < height.shape[1] else np.nan
#         cloudsat_cbh.append(cbh_value)
#
#         # 判断云类型
#         if col_idx < last_idx:
#             between_values = row_data[col_idx + 1:last_idx]  # 从云顶到云底的区域
#             cloud_type = 1 if np.any(between_values < 20) else 0  # 判断云类型
#         else:
#             cloud_type = 0  # 如果云顶和云底相同或无有效数据
#         cloud_types.append(cloud_type)
#
#     else:
#         # 新添加的逻辑，当cloud_radar >= -30但不满足cloud_mask >= 20时
#         radar_valid = cloud_radar[i, :] >= -30
#         if np.any(radar_valid):
#             # 进一步判断cloud_faction是否大于等于99
#             faction_valid = cloud_faction[i, :] >= 99
#             if np.any(faction_valid):
#                 col_idx = np.argmax(faction_valid)
#                 last_idx = np.where(faction_valid)[0][-1]
#
#                 cth_value = height[i, col_idx] if col_idx < height.shape[1] else np.nan
#                 cloudsat_cth.append(cth_value)
#
#                 cbh_value = height[i, last_idx] if last_idx < height.shape[1] else np.nan
#                 cloudsat_cbh.append(cbh_value)
#
#                 # 这里暂时按原逻辑一样处理云类型（可根据实际需求调整）
#                 if col_idx < last_idx:
#                     between_values = row_data[col_idx + 1:last_idx]
#                     cloud_type = 1 if np.any(between_values < 20) else 0
#                 else:
#                     cloud_type = 0
#                 cloud_types.append(cloud_type)
#             else:
#                 cloudsat_cth.append(np.nan)
#                 cloudsat_cbh.append(np.nan)
#                 cloud_types.append(np.nan)
#         else:
#             cloudsat_cth.append(np.nan)
#             cloudsat_cbh.append(np.nan)
#             cloud_types.append(np.nan)
#
#
# data_dict = {
#     'longitude': lon_c,
#     'latitude': lat_c,
#     'cloudsat_cth': cloudsat_cth,
#     'cloudsat_cbh': cloudsat_cbh,
#     'cloudsat_type': cloud_types
# }
#
# # 将字典转换为DataFrame
# df = pd.DataFrame(data_dict)
#
# # 指定CSV文件的保存路径
# csv_filepath = 'cloudsat_2020010101test1.csv'
#
# # 将DataFrame保存为CSV文件
# df.to_csv(csv_filepath, index=False)

import os
import numpy as np
import pandas as pd
from read_CloudSat import reader

# 文件路径
filepath = '/mnt/raid1/liudd/2019365224713_72859_CS_2B-GEOPROF_GRANULE_P1_R05_E09_F00.hdf'
filepath_lida = '/mnt/raid1/liudd/2019365224713_72859_CS_2B-GEOPROF-LIDAR_GRANULE_P2_R05_E09_F00.hdf'

# 读取数据
f = reader(filepath)
d = reader(filepath_lida)
lon_c, lat_c, elv = f.read_geo()
height = f.read_sds('Height')
height = height * 0.001
cloud_mask = f.read_sds('CPR_Cloud_mask')
cloud_radar = f.read_sds('Radar_Reflectivity')
cloud_fraction = d.read_sds('CloudFraction')
time = f.read_time(datetime=True)
cloudsat_start_time, cloudsat_end_time = time[[0, -1]]

cloudsat_cth = []
cloudsat_cbh = []
cloud_types = []

for i in range(len(cloud_mask)):
    row_cloud_mask = cloud_mask[i]
    row_cloud_radar = cloud_radar[i]
    row_cloud_fraction = cloud_fraction[i]

    radar_condition = row_cloud_radar >= -30
    if np.any(radar_condition):
        mask_gte_20 = row_cloud_mask >= 20
        mask_lt_20 = row_cloud_mask < 20

        valid_gte_20 = np.where(radar_condition & mask_gte_20)[0]
        valid_lt_20 = np.where(radar_condition & mask_lt_20)[0]

        if len(valid_gte_20) > 0:
            col_idx = valid_gte_20[0]
            last_idx = valid_gte_20[-1]

            cth_value = height[i, col_idx] if col_idx < height.shape[1] else np.nan
            cloudsat_cth.append(cth_value)

            cbh_value = height[i, last_idx] if last_idx < height.shape[1] else np.nan
            cloudsat_cbh.append(cbh_value)

            if col_idx < last_idx:
                between_values = row_cloud_mask[col_idx + 1:last_idx]
                cloud_type = 1 if np.any(between_values < 20) else 0
            else:
                cloud_type = 0
            cloud_types.append(cloud_type)

        elif len(valid_lt_20) > 0 and np.any(row_cloud_fraction >= 99):
            fraction_valid = row_cloud_fraction >= 99
            col_idx = np.where(fraction_valid)[0][0]
            last_idx = np.where(fraction_valid)[0][-1]

            cth_value = height[i, col_idx] if col_idx < height.shape[1] else np.nan
            cloudsat_cth.append(cth_value)

            cbh_value = height[i, last_idx] if last_idx < height.shape[1] else np.nan
            cloudsat_cbh.append(cbh_value)

            if col_idx < last_idx:
                between_values = row_cloud_mask[col_idx + 1:last_idx]
                cloud_type = 1 if np.any(between_values < 20) else 0
            else:
                cloud_type = 0
            cloud_types.append(cloud_type)

        else:
            cloudsat_cth.append(np.nan)
            cloudsat_cbh.append(np.nan)
            cloud_types.append(np.nan)

    else:
        cloudsat_cth.append(np.nan)
        cloudsat_cbh.append(np.nan)
        cloud_types.append(np.nan)

data_dict = {
    "longitude": lon_c,
    "latitude": lat_c,
    "cloudsat_cth": cloudsat_cth,
    "cloudsat_cbh": cloudsat_cbh,
    "cloudsat_type": cloud_types
}

# 将字典转换为DataFrame
df = pd.DataFrame(data_dict)

# 指定CSV文件的保存路径
csv_filepath = "cloudsat_2020010101test2.csv"

# 将DataFrame保存为CSV文件
df.to_csv(csv_filepath, index=False)